package org.i9.slb.platform.anseko.provider.service;

import org.i9.slb.platform.anseko.common.PowerState;
import org.i9.slb.platform.anseko.provider.IDubboSimulatorRemoteService;
import org.i9.slb.platform.anseko.provider.dto.SimulatorDto;
import org.i9.slb.platform.anseko.provider.repository.SimulatorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * 模拟器远程数据调用服务
 *
 * @author R12
 * @date 2018年9月6日 17:04:48
 */
@Service("dubboSimulatorRemoteService")
public class DubboSimulatorRemoteService implements IDubboSimulatorRemoteService {

    @Autowired
    private SimulatorRepository simulatorRepository;

    /**
     * 获取所有模拟器列表
     *
     * @return
     */
    @Override
    public List<SimulatorDto> getSimulatorDtoList() {
        List<SimulatorDto> simulatorDtos = this.simulatorRepository.getSimulatorDtoList();
        return simulatorDtos;
    }

    /**
     * 获取模拟器详情
     *
     * @param simulatorId
     * @return
     */
    @Override
    public SimulatorDto getSimulatorDtoInfo(String simulatorId) {
        SimulatorDto simulatorDto = simulatorRepository.getSimulatorDtoById(simulatorId);
        return simulatorDto;
    }

    /**
     * 创建模拟器
     *
     * @param simulatorName
     */
    @Override
    public synchronized SimulatorDto createSimulatorInfo(String simulatorName, String instance) {
        SimulatorDto simulatorDto = new SimulatorDto();
        simulatorDto.setInstance(instance);

        simulatorDto.setId(UUID.randomUUID().toString());
        simulatorDto.setCpunum(4);
        simulatorDto.setRamnum(4096);
        simulatorDto.setPowerStatus(PowerState.CLOSE.ordinal());

        // 计算出当前服务器
        int maxVncport = this.simulatorRepository.getSimulatorMaxVNCPort(instance);
        simulatorDto.setVncport(maxVncport == 0 ? 5990 : maxVncport + 1);

        simulatorDto.setVncpassword("i909887");

        simulatorDto.setAndroidVersion("4.0");
        simulatorDto.setSimulatorName(simulatorName);
        this.simulatorRepository.insertSimulator(simulatorDto);

        return simulatorDto;
    }

    /**
     * 删除模拟器
     *
     * @param simulatorId
     */
    @Override
    public void removeSimulatorInfo(String simulatorId) {
        this.simulatorRepository.deleteSimulator(simulatorId);
    }

    /**
     * 更新模拟器状态
     *
     * @param simulatorId
     * @param powerState
     */
    @Override
    public void refreshSimulatorPowerState(String simulatorId, int powerState) {
        this.simulatorRepository.updateSimulatorPowerState(simulatorId, powerState);
    }
}
